<template>
  <div>
    <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="120px" class="demo-ruleForm">
      <el-form-item label="账号" prop="user">
        <el-input v-model="ruleForm.user" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" prop="pass">
        <el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">Submit</el-button>
        <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import pinia from '../../store/store'
import {userInfoStore} from '../../store/userStore'
const store = userInfoStore(pinia)
import { reactive, ref } from "vue";
import { ElMessage } from 'element-plus/es'
import type { FormInstance, FormRules } from "element-plus";
import { LoginFormInt } from "../../type/data"
import {useRouter} from 'vue-router'
const router = useRouter()

const ruleForm: LoginFormInt = reactive({
  user:'',
  pass:''
})
const ruleFormRef = ref<FormInstance>();
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("Please input the password"));
  } else {
    if (ruleForm.pass !== "") {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField("user", () => null);
    }
    callback();
  }
};
const validateUser = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("Please input the user"));
  } else {
    if (ruleForm.user !== "") {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.validateField("user", () => null);
    }
    callback();
  }
}

const rules = reactive<FormRules>({
  pass: [{ validator: validatePass, trigger: "blur" }],
  user: [{ validator: validateUser, trigger: "blur" }],
});

const submitForm = (formEl: FormInstance | undefined) => {
  console.log('ruleForm',ruleForm.user)
  if (!formEl) return;
  let token = ''
  formEl.validate((valid) => {
    if (valid) {
      ElMessage.success('成功')
      if(ruleForm.user == 'admin'){
        token = 'admin'
      }else{
        token = ruleForm.user
      }
      store.setToken('token',token)
      router.replace("/")
    } else {
      ElMessage.error('错误')
      return false;
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>
